/**
 * 程序的入口, 类似java中的main
 */

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';

// 开始引入各种自定义的组件
import Welcome from 'components/Welcome';
import Error from 'components/Error';
import DBTable from 'components/DBTable';

import Footer from 'components/Footer';
import items from './menu.js';
import App from '../Layout';
import ajax from '../../utils/ajax';
// 路由表, 只要menu.js中所有的叶子节点配置了路由就可以了
// 我本来想根据menu.js自动生成路由表, 但那样太不灵活了, 还是自己配置好些
// GWW:改为由routesItems配置
const routesItems = require('route.config.js');
// const arr6 = {
//   children: [{
//     children: [],
//     id: 233,
//     mixId: "xptdv",
//     name: "比赛管理",
//     priority: 1,
//     sn: "User",
//     url: "/cms/manage/CompetitionManage/articleEdit",
//   }],
//   id: 20231,
//   mixId: "b8w29",
//   name: "内容管理",
//   priority: 2312,
//   sn: "SystemManager",
//   url: "#"
// };
// items.push(arr6); //模拟数据

const Home = React.createClass({
  getInitialState() {
    return {
      menu: [],
    };
  },
  componentWillMount() {
    var rootRoute = {
      path: '/',
      getComponent(nextState, cb) {
        require.ensure([], (require) => {
          cb(null, require('../Layout').default)
        }, 'Main')
      },
      indexRoute: {
        getComponent(nextState, cb) {
          require.ensure([], (require) => {
            cb(null, require('components/Welcome').default)
          }, 'Welcome')
        }
      },
      childRoutes: []
    }
    for (var i = 0; i < items.length; i++) {
      var routeItem = { path: items[i].mixId, childRoutes: [] };

      var children = items[i].children;

      for (var j = 0; j < children.length; j++) {
        let routeModel = routesItems[children[j].url];
        // routeModel.getComponent = (location, cb) => {
        //   require.ensure([], require => {
        //     cb(null, require(routeModel.url).default);
        //   }, 'bundle');
        // };
        if (routeModel == null) {
          routeModel = { "path": "", "tableName": "", "component": require('components/DBTable').default };
        }
        else {
          delete routesItems[children[j].url];
        }

        routeItem.childRoutes.push(routeModel);
      }

      rootRoute.childRoutes.push(routeItem);
    }
    for (var item in routesItems) {
      var testItem = routesItems[item];
      rootRoute.childRoutes.push(testItem);

    }
    rootRoute.childRoutes.push({
      path: '*',
      component: require('components/Error').default
    });

    const rootRoute2 = {
      childRoutes: [rootRoute]
    }
    this.menu = rootRoute2;
    console.log(this.menu)
  },
  render() {
    return (
      <Router history={hashHistory} routes={this.menu}></Router>
    );
  }
})

export default Home;